<template>
  <div class="page">
    <div class="page-panel">
      <!-- start 部门详情 -->
      <div class="page-panel-body">
        <!-- start 操作 -->
        <div>
          <span>{{ tagDetailData.serviceProviderName }}</span>
          <div>
            <el-button
              v-if="providerEdit"
              @click="openDepartmentEditPanel(tagDetailData)"
            >
              <i class="iconfont icon-edit-square icon-btn"></i> {{$t('common.base.edit')}}
            </el-button>

            <el-button v-if="providerDelete && !isDel" @click="delDepartment()">
              <i class="iconfont icon-delete"></i> {{$t('common.base.delete')}}
            </el-button>
          </div>
        </div>
        <!-- end 操作 -->
      </div>
      <!-- end 部门详情 -->
    </div>

    <div class="page-main">
      <!-- end左侧 -->
      <div class="page-panel page-main-detail" ref="detail">
        <el-tabs :value="activeTab" @input="handleSwitchTab">
          <!-- 详情 -->
          <el-tab-pane label="详情" name="detailInfo">
            <form-view class="task-tab-container task-view-containner" :fields="tagDetailInfo" :value="tagDetailData">
              <template slot="tagAddress" slot-scope="{ value }">
                <div class="form-view-row">
                  <label>{{$t('common.fields.serviceProviderRegisterAddress.displayName')}}</label>
                  <div class="form-view-row-content">
                    <span
                      class="form-view-row-content form-view-row-content-address"
                      v-if="value"
                      @click="openMap(value)"
                    >
                      <i
                        v-if="
                          value.longitude &&
                          value.latitude
                        "
                        class="iconfont icon-address team-address-icon link-text"
                        style="margin: 0"
                      ></i>
                      <el-tooltip
                        :content="value | fmt_address"
                        placement="top"
                      >
                        <span>{{ value | fmt_address }}</span>
                      </el-tooltip>
                    </span>
                  </div>
                </div>
              </template>

              <!-- 负责区域 -->
              <template slot="tagPlaceList" slot-scope="{ value }">
                <div class="form-view-row">
                  <label>{{$t('common.fields.serviceProviderConstractArea.displayName')}}</label>
                  <div class="form-view-row-content">
                    <template v-for="(item,index) in tagDetailData.tagPlaceList">
                   
                    <span
                      :key="index"
                      class="form-view-row-content form-view-row-content-address"
                      v-if="value"
                      @click="openMap(item)"
                    >
                      <el-tooltip
                        :content="item | fmt_address"
                        placement="top"
                      >
                        <span>{{ item | fmt_address }}</span>
                      </el-tooltip>
                    </span>
                    <br  :key="index" />
                    </template>
                  </div>
                </div>
              </template>

              <!-- 服务商主管 -->
              <template slot="serviceProviderManager">
                <div class="form-view-row">
                  <label>{{$t('common.fields.serviceProviderManager.displayName')}}</label>
                  <div class="form-view-row-content">
                    <template v-if="isOpenData && tagDetailData.serviceProviderManager && tagDetailData.serviceProviderManager.length">
                      <open-data v-for="item in tagDetailData.serviceProviderManager" :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                    </template>
                    <template v-else>
                      {{ teamLeadersName }}
                    </template>
                  </div>
                </div>
              </template>

               <!-- 联系人 -->
              <template slot="serviceProviderContact">
                <div class="form-view-row">
                  <label>{{$t('common.fields.contact.displayName')}}</label>
                  <div class="form-view-row-content">
                    <template v-if="isOpenData && tagDetailData.serviceProviderContact && Object.keys(tagDetailData.serviceProviderContact).length">
                      <open-data v-for="item in tagDetailData.serviceProviderContact" :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                    </template>
                    <template v-else>
                      {{ teamContactName }}
                    </template>
                  </div>
                </div>
              </template>

              <!-- 标签 -->
              <template slot="labelNames" slot-scope="{value}">
                <div class="form-view-row">
                  <label>{{$t('common.fields.tags.displayName')}}</label>
                  <div class="form-view-row-content">{{ value.join("，") }}</div>
                </div>
              </template>
            </form-view>
          </el-tab-pane>

          <!-- 子部门 -->
          <el-tab-pane :label="$t('common.base.subServiceProvider')" name="childTagList">
            <service-child-list
              v-if="tagId && activeTab == 'childTagList'"
              :initData="initData"
              :detailId="tagDetailData.tagId"
              @childDel="(e) => delDepartment(e)"
              @childEdit="(e) => openDepartmentEditPanel(e)"
            ></service-child-list>
          </el-tab-pane>

          <!-- 成员列表 -->
          <el-tab-pane :label="$t('common.base.memberList')" name="userList">
            <dept-user-list
              v-if="tagId && activeTab == 'userList'"
              :detailId="tagId"
            ></dept-user-list>
          </el-tab-pane>

          <!-- 服务事件 -->
          <el-tab-pane :label="$t('common.base.serviceEvent')" name="eventsForUserList">
            <dept-events-list
              v-if="tagId && activeTab == 'eventsForUserList'"
              :detailId="tagId"
            ></dept-events-list>
          </el-tab-pane>

          <!-- 工单列表 -->
          <el-tab-pane :label="$t('common.label.taskList')" name="tasksForUserView">
            <dept-tasks-list
              v-if="tagId && activeTab == 'tasksForUserView'"
              :detailId="tagId"
            ></dept-tasks-list>
          </el-tab-pane>
            <!--结算单 -->
          <el-tab-pane :label="$t('common.label.balanceOrder')" name="settleForUserList" v-if="openSettleGray">
            <service-settle-list
                v-if="tagId && activeTab === 'settleForUserList'"
                :detail-id="tagId"
            ></service-settle-list>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- end左侧 -->

      <!-- start 右侧 -->
      <div class="page-panel page-main-addition" ref="addition">
        <div class="page-main-addition-header">{{$t('common.base.dynamic')}}</div>
        <!-- 搜索选择 -->
        <dept-records v-if="tagId" :detailId="tagId"></dept-records>
      </div>
      <!-- end 右侧 -->
    </div>

    <!-- start 编辑 -->
    <el-dialog :visible.sync="deptDialogVisible" :show-close="true">
      <team-edit-view ref="team" :id="deptEditId"></team-edit-view>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">{{$t('common.base.confirm')}}</el-button>
      </span>
    </el-dialog>
    <!-- end 编辑 -->
  </div>
</template> 

<script>
import { isOpenData } from '@src/util/platform'
/*global AMap, moment, _init_data*/
import * as serviceProviderHomeApi from "@src/api/serviceProviderHomeApi";
import * as serviceProviderApi from "@src/api/serviceProviderApi";

import _ from "lodash";

import Page from "@src/model/Page";

// components
import TeamEditView from "@src/modules/serviceProvider/component/CreateTeamPanel.vue";

import ServiceChildList from "./components/ServiceChildList.vue";
// 部门主页和服务商主页 一样的组件
import DeptEventsList from "@src/modules/dept/deptHome/components/DeptEventsList.vue";
import DeptUserList from "@src/modules/dept/deptHome/components/DeptUserList.vue";
import DeptTasksList from "@src/modules/dept/deptHome/components/DeptTasksList.vue";
import DeptRecords from "@src/modules/dept/deptHome/components/DeptRecords.vue";
import ServiceSettleList from './components/ServiceSettleList';

export default {
  name: "service-home",
  inject: ["initData"],
  components: {
    ServiceSettleList,
    [TeamEditView.name]: TeamEditView,

    [ServiceChildList.name]: ServiceChildList,
    [DeptEventsList.name]: DeptEventsList,
    [DeptUserList.name]: DeptUserList,
    [DeptTasksList.name]: DeptTasksList,
    [DeptRecords.name]: DeptRecords,
    [ServiceSettleList.name]: ServiceSettleList,
  },
  data() {
    return {
      isOpenData,
      activeTab: "detailInfo", // 选中的tabs
      pageInfo: {
        // 分页
        pageNum: 1,
        pageSize: 10,
      },
      total: 0, // 总数

      tagDetailData: {}, // 详情数据
      recordsList: [], // 动态

      recordsSelect: "all",
      recordsData: {
        createTimeStart: "",
        createTimeEnd: "",
      },
      deptDialogVisible: false, // 编辑弹窗
      deptEditId: "",
      depts: [],
      isDel: false,
      openSettleGray: false, //服务商结算单灰度
    };
  },
  computed: {
    // 详情id
    detailId() {
      return window.location.pathname.split(
        "/security/tag/serviceProviderHome/"
      )[1];
    },
    // 详情展示名称
    tagDetailInfo() {
      return [
        { displayName: this.$t('common.fields.providerName.displayName'), fieldName: "serviceProviderName",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.fields.providerName.displayName'), fieldName: "serviceProviderAttribute",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.base.companyName_1'), fieldName: "registerCompanyName",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.base.usci'), fieldName: "creditCode",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.fields.serviceProviderLegalRepresentative.displayName'), fieldName: "legalPerson",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.fields.serviceProviderRegisterAddress.displayName'), fieldName: "tagAddress",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.fields.serviceProviderConstractArea.displayName'), fieldName: "tagPlaceList",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.fields.serviceProviderManager.displayName'), fieldName: "serviceProviderManager",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.fields.contact.displayName'), fieldName: "serviceProviderContact",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.fields.contactNumber.displayName'), fieldName: "linkPhone",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.fields.weChatId.displayName'), fieldName: "wechat",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.fields.email.displayName'), fieldName: "email",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.fields.tags.displayName'), fieldName: "labelNames",formType:'text',isSystem: 1 },
        { displayName: this.$t('common.tabs.additionContractList'), fieldName: "contract",formType:'attachment',isSystem: 1 },
        { displayName: this.$t('common.fields.skillsCertificate.displayName'), fieldName: "skillCertificate",formType:'attachment',isSystem: 1 },
      ];
    },
    // 服务商主管
    teamLeadersName() {
      return (
        this.tagDetailData.serviceProviderManager &&
        this.tagDetailData.serviceProviderManager
          .map((i) => (i && i.displayName) || "")
          .join("，")
      );
    },
    // 负责人
    teamContactName() {
       return this.tagDetailData?.serviceProviderContact?.displayName ? this.tagDetailData.serviceProviderContact.displayName :''
    },
    tagId() {
      return this.tagDetailData.tagId;
    },
    // 获取标签
    authorities() {
      return this.initData.authorities || {};
    },
    // 删除服务商
    providerDelete() {
      return "PROVIDER_DELETE" in this.authorities;
    },
    // 编辑服务商
    providerEdit() {
      return "PROVIDER_EDIT" in this.authorities;
    },
    // 服务商页面的tabid
    parentTab(variable){
      const query = window.location.search.substring(1);
      return query.split('=')[1];
    }
  },
  async mounted() {
    this.depts = await this.fetchDept();

    await this.getSerTagDetail();
    await this.getIsDel();
  },
  methods: {
    // 部门详情
    getSerTagDetail() {
      serviceProviderHomeApi
        .getSerTagDetail({
          id: this.detailId,
        })
        .then((res) => {
          const { status, message, data } = res;
          if (status !== 0) return;
          this.openSettleGray = data.settleGray
          this.tagDetailData = data;

          const {
          address,
          addressType,
          city,
          dist,
          latitude,
          longitude,
          province,
          country
        } = data;
        this.tagDetailData.tagAddress = {
          address,
          addressType,
          city,
          dist,
          latitude,
          longitude,
          province,
          country
        };
        });
    },
    // 是否可以删除
    getIsDel() {
      serviceProviderHomeApi.getIsDel()
        .then((res) => {
          const { status, message, data } = res;
          if (status !== 0) return;
          
          this.isDel = data.some( x => x == this.tagDetailData.tagId);
        });
    },
    // 切换tabs
    handleSwitchTab(e) {
      this.activeTab = e;
    },
    // 编辑弹窗
    openDepartmentEditPanel(row) {
      this.deptEditId = row.id;
      this.deptDialogVisible = true;
    },
    // 提交编辑
    submit() {
      this.$refs.team.submit((params) => {
        serviceProviderApi.edit(params).then((r) => {
          const state = r.status == 0;
          this.$platform.notification({
            type: state ? "success" : "error",
            title: this.$t('serviceProvider.editProviederStatus', {status: state ? "成功" : "失败"}),
            message: state ? null : r.message,
          });
          this.submitAddDept();
        });
      });
    },
    // 更新详情
    submitAddDept() {
      this.deptDialogVisible = false;
      this.getSerTagDetail(false);

      // 更新服务商页面内容
      if(this.parentTab) this.$platform.refreshTab(this.parentTab);
    },
    /** 抓取服务商数据 */
    fetchDept() {
      let params = {
        seeAllOrg: false,
        keyword: "",
      };

      return serviceProviderApi
        .tree(params)
        .then((result) => {
          return (result && result.data) || [];
        })
        .catch((err) => console.error("err", err));
    },
    // 是否展示删除
    isRootDepartment(department = {}) {
      return this.depts.some((dept) => dept.id == department.id);
    },
    // 删除
    async delDepartment(id) {
      // 您删除的团队，如果包含子团队将会一并删除，是否继续？
      try {
        if (
          await this.$platform.confirm(
            this.$t('serviceProvider.deleteProviederTip')
          )
        ) {
          let ids = [this.tagDetailData.id];
          if (id) ids = [id];
          let result = await serviceProviderApi.serviceProviderDelete(ids);

          const state = result.status == 0;
          this.$platform.notification({
            type: state ? "success" : "error",
            title: this.$t('serviceProvider.deleteProviederStatus', {status: state ? "成功" : "失败"}),
            message: state ? null : result.message,
          });

          if (state) {
            // 更新服务商页面内容
            if(this.parentTab) this.$platform.refreshTab(this.parentTab);

            let id = window.frameElement.dataset.id;
            this.$platform.closeTab(id);
          }
        }
      } catch (e) {
        console.error("teamDelete catch error", e);
      }
    },
    openMap(item) {
      this.$fast.map
        .display(item, { title: this.$t('common.label.departmentLocation') })
        .catch((err) => console.error("openMap catch an err: ", err));
    },
  },
};
</script>

<style lang="scss">
.page {
  height: 100%;
  padding: 12px;
}
.service-price-delete {
  float: right;
  color: #f56c6c;
}

.page-panel-body {
  overflow: hidden;
  clear: both;
  > div:first-child {
    display: flex;
    align-items: center;
    justify-content: space-between;
    > span {
      font-size: 16px;
      font-weight: 500;
    }
  }
}

.detail-list-box {
  display: flex;
  flex-direction: column;

  > div {
    padding-right: 64px;
    font-size: 14px;
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    > span {
      width: 130px;
    }

    > p {
      margin: 0;
      flex: 1;
      color: #595959;
      @include text-ellipsis();
    }
  }
}

.page-main {
  min-height: calc(100% - 70px);
}

.page-main-detail {
  overflow: auto;
  flex: 7;
}

.page-main-addition {
  overflow: hidden;
  flex: 3;

  .page-main-addition-header {
    height: 40px;
    line-height: 40px;
    background-color: $bg-color-l2;
    padding: 0 16px;
    border-bottom: 1px solid $color-border-l3;
  }

  .progress-content {
    padding: 16px;
    .page-right-search {
      display: flex;
      flex-direction: column;
      > div {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        > span {
          min-width: 70px;
        }
        > div {
          flex: 1;
        }
      }
    }
  }
}

.icon-btn {
  vertical-align: middle;
  font-size: 18px;
}
.base-modal-mask {
  z-index: 5000;
}
.amap-sug-result {
  z-index: 5001;
}
</style>

<style lang="scss" scoped>
::v-deep .page-main-detail .el-tabs__nav-scroll {
  padding: 0 16px;
  background-color: $bg-color-l2;
}
::v-deep .page-main-detail .el-tabs__content {
  padding: 1px 16px 16px;
}
::v-deep .el-tabs__nav-wrap::after {
  height: 1px;
}
.page .el-date-editor {
  padding: 0 !important;
}

::v-deep .el-dialog__wrapper {
  z-index: 3000 !important;
}
</style>